from django.http import JsonResponse
from django.db.models import Sum
from mysite.models import Admins, Users, Lessons
from django.core.cache import cache
from django.db import transaction
import hashlib,uuid


# Create your views here.


def check_token(userid, token, admin=False):
    if not token:
        return None
    if admin:
        user_info = Admins.objects.filter(userid=userid, token=token).first()
    else:
        user_info = Users.objects.filter(userid=userid, token=token).first()
    if not user_info:
        return None
    else:
        return user_info

def login(request):
    userid = request.POST.get("userid")
    password = request.POST.get("password")
    admin = request.POST.get("admin")
    if len(userid) <= 0 or len(userid) > 20:
        return JsonResponse({"login": "false"})
    if len(password) <= 0 or len(password) > 20:
        return JsonResponse({"login": "false"})
    if userid in cache:
        if cache.get(userid) >= 3:
            return JsonResponse({"login": "false", "login_wait": cache.ttl(userid)})
    password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
    token = check_login(userid, password, admin)
    if token:
        return JsonResponse({"login": "true", "token": token})
    else:
        if userid in cache:
            login_cnt = cache.get(userid)
            cache.set(userid, login_cnt+1, 30)
            if cache.get(userid) >= 3:
                return JsonResponse({"login": "false", "login_wait": cache.ttl(userid)})
            else:
                return JsonResponse({"login": "false", "login_cnt": cache.get(userid)})
        else:
            cache.set(userid, 1, 30)
            return JsonResponse({"login": "false", "login_cnt": cache.get(userid)})


def check_login(userid, password, admin):
    if admin:
        user_info = Admins.objects.filter(userid=userid, password=password).first()
    else:
        user_info = Users.objects.filter(userid=userid, password=password).first()
    if not user_info:
        return None
    else:
        token = str(uuid.uuid4())
        try:
            user_info.token = token
            user_info.save()
            return token
        except Exception as e:
            print(e)
            return None


def register(request):
    userid = request.POST.get("userid")
    password = request.POST.get("password")
    if len(userid) <= 0 or len(userid) > 20:
        return JsonResponse({"register": "false"})
    if len(password) <= 0 or len(password) > 20:
        return JsonResponse({"register": "false"})
    password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
    token = do_register(userid, password)
    if token:
        return JsonResponse({"register": "true", "token": token})
    else:
        return JsonResponse({"register": "false"})


def do_register(userid, password):
    user_info = Users.objects.filter(userid=userid)
    if len(user_info) > 0:
        return None
    try:
        token = str(uuid.uuid4())
        user_info = Users(userid=userid, password=password, token=token)
        user_info.save()
        return token
    except Exception as e:
        print(e)
        return None


def get_lesson(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    get_lesson_userid = request.POST.get("get_lesson_userid")
    if get_lesson_userid:
        user_info = check_token(userid, token, True)
    else:
        user_info = check_token(userid, token)
    if user_info:
        if get_lesson_userid:
            user_info = Users.objects.filter(userid=get_lesson_userid).first()
        lesson = user_info.tlesson
    else:
        return JsonResponse({"get_lesson": "操作失败，请重新登录"})
    if lesson:
        return JsonResponse({"get_lesson": "操作失败，已选上此课程", "lesson": "1"})
    lessons_info = s.objects.all()[0]
    lessons = lessons_info.lessons
    if lessons <= 0:
        return JsonResponse({"get_lesson": "操作失败，名额不足", "lesson": "0"})
    try:
        with transaction.atomic():
            lessons_info.lessons = lessons - 1
            lessons_info.save()
            cache.set("lessons", lessons - 1, 30)
            user_info.lesson = 1
            user_info.save()
            return JsonResponse({"get_lesson": "操作成功", "lesson": "1", "lessons": lessons-1})
    except Exception as e:
        print(e)
        return JsonResponse({"get_lesson": "操作失败"})


def return_lesson(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    return_lesson_userid = request.POST.get("return_lesson_userid")
    if return_lesson_userid:
        user_info = check_token(userid, token, True)
    else:
        user_info = check_token(userid, token)
    if user_info:
        if return_lesson_userid:
            user_info = Users.objects.filter(userid=return_lesson_userid).first()
        lesson = user_info.lesson
    else:
        return JsonResponse({"return_lesson": "操作失败，请重新登录"})
    if lesson == 0:
        return JsonResponse({"return_lesson": "操作失败", "lesson": "0"})
    lessons = Lessons.objects.all()[0].lessons
    try:
        with transaction.atomic():
            Lessons.objects.all().update(lessonts=lessons+1)
            cache.set("lessons", lessons + 1, 30)
            user_info.lesson = 0
            user_info.save()
            return JsonResponse({"return_lesson": "操作成功", "lesson": "0", "lessons": lessons+1})
    except Exception as e:
        print(e)
        return JsonResponse({"return_lesson": "操作失败"})


def check_lesson(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    user_info = check_token(userid, token)
    if not user_info:
        return JsonResponse({"error": "请重新登录"})
    if "lessons" in cache:
        lessons = cache.get("lessons")
    else:
        lessons = Lessons.objects.all()[0].lessons
        cache.set("lessons", lessons, 30)
    userid = request.POST.get("userid")
    lesson = Users.objects.get(userid=userid).lesson
    return JsonResponse({"lessons": lessons, "lesson": int(lesson)})


def show_lessons(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    user_info = check_token(userid, token, True)
    if not user_info:
        return JsonResponse({"error": "请重新登录"})

    if "lessons" in cache:
        lessons = cache.get("lessons")
    else:
        lessons = Lessons.objects.all()[0].lessons
        cache.set("lessons", lessons, 30)

    if "total_lessons" in cache:
        total_lessons = cache.get("total_lessons")
    else:
        total_lessons = Lessons.objects.all()[0].total_lessons
        cache.set("total_lessons", total_lessons, 30)
    return JsonResponse({"lessons": lessons, "total_lessons": total_lessons})


def change_lessons(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    user_info = check_token(userid, token, True)
    if not user_info:
        return JsonResponse({"error": "请重新登陆"})

    total_lessons = request.POST.get("new_lessons")
    if not total_lessons.isdigit() or len(total_lessons) <= 0 or len(total_lessons) > 20:
        return JsonResponse({"change_lessons_res": "请输入整数"})
    if len(Lessons.objects.all()) == 0:
        Lessons().save()
    total_lessons = int(request.POST.get("new_lessons"))
    if len(Users.objects.all()) > 0:
        lessons = total_lessons - Users.objects.aggregate(lessons=Sum('lesson'))['lessons']
    else:
        lessons = total_lessons
    if lessons >= 0:
        try:
            with transaction.atomic():
                Lessons.objects.all().update(total_lessons=total_lessons)
                Lessons.objects.all().update(lessons=lessons)
                cache.set("total_lessons", total_lessons, 30)
                cache.set("lessons", lessons, 30)
                return JsonResponse({"lessons": lessons, "total_lessons": total_lessons,
                                     "change_lessons_res": "修改成功"})
        except Exception:
            return JsonResponse({"change_lessons_res": "修改失败"})
    else:
        return JsonResponse({"change_lessons_res": "已选课人数多于输入人数，修改失败"})


def show_users(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    user_info = check_token(userid, token, True)
    if not user_info:
        return JsonResponse({"error": "请重新登录"})

    users = Users.objects.all()
    user_ids = []
    lessons = []
    for user in users:
        user_ids.append(user.userid)
        lessons.append(int(user.lesson))
    return JsonResponse({"user_ids": user_ids, "lessons": lessons, "user_cnt": len(user_ids)})


def delete_user(request):
    userid = request.POST.get("userid")
    token = request.POST.get("token")
    user_info = check_token(userid, token, True)
    if not user_info:
        return JsonResponse({"error": "请重新登录"})

    userid = request.POST.get("delete_userid")
    user_info = Users.objects.filter(userid=userid)
    if len(user_info) > 0:
        lesson = user_info[0].lesson
        lessons = Lessons.objects.all()[0].lessons
        try:
            with transaction.atomic():
                Lessons.objects.all().update(lessons=lessons + lesson)
                cache.set("lessons", lessons + lesson, 30)
                user_info.delete()
                return JsonResponse({"msg": "成功删除用户" + userid})
        except Exception:
            return JsonResponse({"msg": "删除用户" + userid + "失败"})
    else:
        return JsonResponse({"msg": "用户" + userid + "不存在"})
